﻿using System.Security.Cryptography;
using System.Text;

namespace DoNet.Common.Helper
{
    public class EncryptHelper
    {
        /// <summary>
        /// 获取大写的MD5签名结果
        /// </summary>
        /// <param name="encypStr">需要加密的字符串</param>
        /// <param name="encoding">编码 （为null时，默认为Encoding.UTF8）</param>
        /// <returns></returns>
        public static string GetMD5(string encypStr, Encoding? encoding = null)
        {
            if(encoding == null)
            {
                encoding = Encoding.UTF8;
            }
            return BitConverter.ToString(MD5.Create().ComputeHash(encoding.GetBytes(encypStr))).Replace("-", "").ToUpper();
        }

        /// <summary>
        /// 获取小写的MD5签名结果
        /// </summary>
        /// <param name="encypStr">需要加密的字符串</param>
        /// <param name="encoding">编码 （为null时，默认为Encoding.UTF8）</param>
        /// <returns></returns>
        public static string GetMD5Lower(string encypStr, Encoding encoding)
        {
            return GetMD5(encypStr, encoding).ToLower();
        }

        /// <summary>
        /// 获取MD5签名结果
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="toUpper">是否返回大写结果，true：大写，false：小写</param>
        /// <returns></returns>
        public static string GetMD5(Stream stream, bool toUpper = true)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stream.Position = 0L;
            byte[] array = MD5.Create().ComputeHash(stream);
            for (int i = 0; i < array.Length; i++)
            {
                stringBuilder.Append(array[i].ToString(toUpper ? "X2" : "x2"));
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 采用SHA-1算法加密字符串（小写）
        /// </summary>
        /// <param name="encypStr">需要加密的字符串</param>
        /// <returns></returns>
        public static string GetSha1(string encypStr)
        {
            return GetSha1(encypStr, toUpper: false);
        }

        /// <summary>
        /// 采用SHA-1算法加密字符串（默认大写）
        /// </summary>
        /// <param name="encypStr">需要加密的字符串</param>
        /// <param name="toUpper">是否返回大写结果，true：大写，false：小写</param>
        /// <param name="encoding">编码 （为null时，默认为Encoding.UTF8）</param>
        /// <returns></returns>
        public static string GetSha1(string encypStr, bool toUpper = true, Encoding? encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            StringBuilder stringBuilder = new StringBuilder();
            byte[] array = SHA1.Create().ComputeHash(encoding.GetBytes(encypStr));
            foreach (byte b in array)
            {
                stringBuilder.AppendFormat("{0:x2}", b);
            }

            if (!toUpper)
            {
                return stringBuilder.ToString();
            }

            return stringBuilder.ToString().ToUpper();
        }

        /// <summary>
        /// 采用SHA-1算法加密流（默认大写）
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="toUpper">是否返回大写结果，true：大写，false：小写</param>
        /// <returns></returns>
        public static string GetSha1(Stream stream, bool toUpper = true)
        {
            stream.Seek(0L, SeekOrigin.Begin);
            StringBuilder stringBuilder = new StringBuilder();
            byte[] array = SHA1.Create().ComputeHash(stream);
            foreach (byte b in array)
            {
                stringBuilder.AppendFormat("{0:x2}", b);
            }

            string text = stringBuilder.ToString();
            if (!toUpper)
            {
                return text;
            }

            return text.ToUpper();
        }

        /// <summary>
        /// HMAC SHA256 加密
        /// </summary>
        /// <param name="text">加密消息原文。（当为小程序SessionKey签名提供服务时，其中message为本次POST请求的数据包（通常为JSON）。特别地，对于GET请求，message等于长度为0的字符串。）</param>
        /// <param name="key">秘钥（如小程序的SessionKey、微信商户支付密钥）</param>
        /// <returns></returns>
        public static string GetHmacSha256(string text, string key)
        {
            text = text ?? "";
            key = key ?? "";
            StringBuilder stringBuilder = new StringBuilder();
            byte[] bytes = Encoding.UTF8.GetBytes(key);
            byte[] bytesText = Encoding.UTF8.GetBytes(text);
            byte[] array = new HMACSHA256(bytes).ComputeHash(bytesText);
            foreach (byte b in array)
            {
                stringBuilder.AppendFormat("{0:x2}", b);
            }
            return stringBuilder.ToString();
        }
    }
}
